﻿using System;

namespace DAPNet
{
    internal class HighPassFilter : IOfflineEffect
    {
        private double sampleRate;

        private double cutoffFrequency;

        private double previousInputSample;

        private double previousOutputSample;

        private double alpha;


        internal HighPassFilter(double sampleRate, double cutoffFrequency)
        {
            this.sampleRate = sampleRate;
            this.cutoffFrequency = cutoffFrequency;
            ResetAlpha();
        }

        internal double SampleRate
        {
            get
            {
                return sampleRate;
            }
            set
            {
                sampleRate = value;
                ResetAlpha();
            }
        }

        internal double CutoffFrequency
        {
            get
            {
                return cutoffFrequency;
            }
            set
            {
                cutoffFrequency = value;
                ResetAlpha();
            }
        }

        public void Process(SampleCollection samples)
        {
            ResetState();
            for (int i = 0; i < samples.Count; i++)
            {
                double value = samples[i].Value;
                double processedValue = Process(value);
                samples[i].SetTrimmedValue(processedValue);
            }
        }

        private double Process(double value)
        {
            previousOutputSample = alpha * (previousOutputSample + value - previousInputSample);
            previousInputSample = value;
            return previousOutputSample;
        }

        private void ResetState()
        {
            previousInputSample = Sample.BaseValue;
            previousOutputSample = Sample.BaseValue;
        }

        private void ResetAlpha()
        {
            double RC = 1 / (2 * Math.PI * cutoffFrequency);
            double samplingInterval = 1 / sampleRate;
            alpha = RC / (RC + samplingInterval);
        }
    }
}
